package com.ukao.pad.utils;


import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;


import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;

import com.ukao.pad.R;
import com.ukao.pad.bean.uploadItem;
import com.ukao.pad.widget.ZProgressHUD;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;


public class UploadUtils {


    private List<String> mImageList;

    private OnOSSFileUploadFinish mOnOSSFileUploadFinish;
    private final int COMPRESS_SUCCESS = 2;
    private final int MSG_UPLOAD_SUCCESS = 3;
    private final int MSG_UPLOAD_FAILED = 4;
    private final int MSG_UPLOAD_PROGRES = 5;
    private int nCurIndex = 0;

    private List<String> compressedFiles ;/*压缩图片集合*/
    private String localiamg;
    private String video;
    private String videoIamg;
    private   String  token;
    private ArrayList<uploadItem> uploadlist;
    public ZProgressHUD pd=null;
    private UploadManager uploadManager;



    public interface OnOSSFileUploadFinish {
        void OnUploadFinish(String image, String video, String videoImage);

    }


    /**
     * 压缩   上传图片
     *
     * @param mImageList             图片文件
     * @param mOnOSSFileUploadFinish 上传成功回调
     */
    public void startImageUpload(Context context,String  token, List<String> mImageList, OnOSSFileUploadFinish mOnOSSFileUploadFinish ) {

        nCurIndex = 0;
        uploadlist = new ArrayList<uploadItem>();
        compressedFiles = new ArrayList<String>();/*压缩图片集合*/
        this.token=token;
        this.mImageList = mImageList;
        this.mOnOSSFileUploadFinish = mOnOSSFileUploadFinish;
        if (pd==null){
            pd= ZProgressHUD.getInstance(context);
        }
        pd.setCanceledOnTouchOutside(false);
        pd.show();
        handler.sendEmptyMessage(COMPRESS_SUCCESS);


    }






    Handler handler = new Handler() {


        public void handleMessage(Message msg) {
            switch (msg.what) {

                case COMPRESS_SUCCESS:
                    for (int i = 0; i < mImageList.size(); i++) {
                        AddPhoto(mImageList.get(i));
                    }
                    uploadfiles();

                    break;

                case MSG_UPLOAD_FAILED:
                    String errors = msg.getData().getString("error");
                    T.show( errors);
                    if (pd != null) {
                        pd.dismiss();
                    }
                    break;
                case MSG_UPLOAD_SUCCESS: //
                    uploadItem item = uploadlist.get(nCurIndex);
                    item.setIsUploaded(true);
                    nCurIndex = nCurIndex + 1;
                    uploadfiles();
                    break;
                case MSG_UPLOAD_PROGRES:

                    if (pd!= null) {
                        double currentSize = msg.getData().getDouble("currentSize");
                        double f = currentSize;
                        DecimalFormat df = new DecimalFormat("######0.00");
                        String tmp = uploadlist.get(nCurIndex).getType();
                        String msginfo = Utils.getContext().getString(R.string.uploading);
                        int number = nCurIndex + 1;
                        if (tmp.equals("image")) {
                            msginfo = "上传第" + number + "张图片  ";
                        } else if (tmp.equals("video")) {
                            msginfo = "上传视频文件  ";
                        }
                        String msgString = msginfo + df.format(f) + "%";
                        pd.setMessage(msgString);
                    }
                    break;
            }
        }

        ;
    };


    public void AddPhoto(String src ) {
        uploadItem item = new uploadItem("image");
        item.setLocalfile(src);
        String des = "";
        if (src.substring(0, 4).equals("http")) {
        //    des = IURL.getInstance().getPartUrl(src);
      //      item.setIsUploaded(true);

        } else {
            des ="android/product"+ getStringNow() + ".jpg";
            item.setIsUploaded(false);
            /*设置视频是否是视频图片*/
            item.setRemotefile(des);
            uploadlist.add(item);

        }


    }

    private void addvideofile(String videoFile) {


        uploadItem videoItem = new uploadItem("video");
        videoItem.setLocalfile(videoFile);
        String videoString = "";
        if (videoFile.substring(0, 4).equals("http")) {
         //   videoString = IURL.getInstance().getPartUrl(videoFile);
          //  videoItem.setIsUploaded(true);
        } else {
            videoString = "videos/" + getStringNow() + ".mp4";
            videoItem.setIsUploaded(false);
            videoItem.setRemotefile(videoString);
            uploadlist.add(videoItem);
        }

    }

    private void uploadfiles() {
        if (nCurIndex < uploadlist.size()) {
            String localfile = uploadlist.get(nCurIndex).getLocalfile();
            String remotefile = uploadlist.get(nCurIndex).getRemotefile();

            if (uploadlist.get(nCurIndex).getIsUploaded()) {
                nCurIndex = nCurIndex + 1;
                uploadfiles();
            } else {
                uploadFile(localfile, remotefile);
            }
        } else {
            if (pd != null) {
                pd.dismiss();
            }

            appendOssFileName();

        }

    }


    /**
     * 拼接上传阿里云的名字
     */

    public void appendOssFileName() {


        if (uploadlist != null) {


            localiamg = "";
            videoIamg = "";
            JSONArray mJSONArray=new JSONArray();
            for (int i = 0; i < uploadlist.size(); i++) {
                uploadItem item = uploadlist.get(i);
                if (item.getType().equals("image")) {
                   // localiamg=localiamg+item.getRemotefile() + ";";
                    try {
                        JSONObject   mJSONObject=new JSONObject();
                        mJSONObject.put("cameraImg",item.getRemotefile());
                        mJSONArray.put(mJSONObject);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else if (item.getType().equals("video")) {
                    video = item.getRemotefile();
                }

            }


            if (mJSONArray.length()!=0){
                localiamg=mJSONArray.toString();
            }
//            if (!TextUtils.isEmpty(localiamg)) {
//                localiamg = localiamg.substring(0,localiamg.length() - 1);
//
//            }


        }

        mOnOSSFileUploadFinish.OnUploadFinish(localiamg, video, videoIamg);
    }






    private void uploadFile(final String localFile,final String ossName) {

        if (this.uploadManager== null) {
            this.uploadManager= new UploadManager();
        }

        final UploadOptions uploadOptions = new UploadOptions(null, null, false,
                new UpProgressHandler() {
                    @Override
                    public void progress(String key, double currentSize) { /*升级进度*/
                        Message msg = Message.obtain();
                        Bundle mBundle = new Bundle();
                        mBundle.putDouble("currentSize",currentSize);
                        msg.setData(mBundle);
                        msg.what = MSG_UPLOAD_PROGRES;
                        handler.sendMessage(msg);
                    }
                }, null);
        new Thread(new Runnable() {

            @Override
            public void run() {

                uploadManager.put(localFile,ossName, token,
                        new UpCompletionHandler() {
                            @Override
                            public void complete(String key, ResponseInfo info, JSONObject res) {
                                if(info.isOK()) {
                                    handler.sendEmptyMessage(MSG_UPLOAD_SUCCESS);
                                } else {
                                    Message msg = Message.obtain();
                                    Bundle mBundle = new Bundle();
                                    mBundle.putString("error", "上传失败");
                                    msg.setData(mBundle);
                                    msg.what = MSG_UPLOAD_FAILED;
                                    handler.sendMessage(msg);

                                }

                            }
                        },uploadOptions
                );
            }
        }).start();




    }

    public static String getStringNow() {
        return getRandomString(5)+System.currentTimeMillis();
    }
    /**
     * 随机生成字符串
     *
     * @return
     */
    public static String getRandomString(int length) {
        StringBuffer buffer = new StringBuffer(
                "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
        StringBuffer sb = new StringBuffer();
        Random random = new Random();
        int range = buffer.length();
        for (int i = 0; i < length; i++) {
            sb.append(buffer.charAt(random.nextInt(range)));
        }
        return sb.toString();
    }


}
